package jalus.blog;

import jalus.Action;
import jalus.model.Post;
import jalus.pojo.Pageindicator;
import jalus.service.CommentService;
import jalus.service.ConfigureService;
import jalus.service.PostService;
import jalus.service.TagService;
import jalus.service.WidgetService;
import jalus.utils.CaptchaUtils;
import jalus.utils.HttpUtils;
import jalus.utils.MyUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class PostServlet extends Action{
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)	throws IOException {
		String action = req.getParameter("action");
		if(StringUtils.equalsIgnoreCase(action, "view")){
			viewPost(req, resp);
		}else if(StringUtils.equalsIgnoreCase(action, "new")){
			newPost(req, resp);
		}else if(StringUtils.equalsIgnoreCase(action, "delete")){
			deletePost(req, resp);
		}else if(StringUtils.equalsIgnoreCase(action, "edit")){
			editPost(req, resp);
		}else if(StringUtils.equalsIgnoreCase(action, "archive")){
			listArchive(req, resp);
		}else{
			action = "list";
			list(req, resp);
		}
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String action = req.getParameter("action");
		if(StringUtils.equalsIgnoreCase(action, "new")){
			addPost(req, resp);
		}else if(StringUtils.equalsIgnoreCase(action, "edit")){
			updatePost(req, resp);
		}else{
			error();
		}
	}
	
	/**
	 * 更新Post
	 * @param req
	 * @param resp
	 * @throws IOException 
	 */
	private void updatePost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		if(!userService.isUserLoggedIn() || !userService.isUserAdmin()){
			error();
			return;
		}
		User user = userService.getCurrentUser();
		
		long postid = NumberUtils.toLong(req.getParameter("postid"));
		String title = req.getParameter("title");
		String[] tagArray = req.getParameterValues("tags");
		List<String> tags;
		if(tagArray == null){
			tags = new ArrayList<String>(0);
		} else {
			tags = Arrays.asList(tagArray);
		}
		Integer privilege = new Integer(req.getParameter("privilege"));
		String content = req.getParameter("content");
		String dateStr = req.getParameter("pubdate");
		Date date = MyUtils.parseDateCCT(dateStr, "yyy-MM-dd HH:mm");
		content = HttpUtils.tranlateSourceCode(content);
        Post newPost = new Post(user, title, privilege, new Text(content), date, tags);
        newPost.setLast_modify_date(date);
        newPost.setLast_modify_by(user);
        newPost.setId(postid);
		PostService postService = PostService.getInstance();
		postService.updatePost(newPost);
		resp.sendRedirect("/blog/post?action=view&postid=" + postid);
	}

	/**
	 * 新建Post
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	private void addPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		if(!userService.isUserLoggedIn() || !userService.isUserAdmin()){
			error();
			return;
		}
		
		User user = userService.getCurrentUser();
		String title = req.getParameter("title");
		String[] tagArray = req.getParameterValues("tags");
		List<String> tags;
		if(tagArray == null){
			tags = new ArrayList<String>(0);
		} else {
			tags = Arrays.asList(tagArray);
		}
		int privilege = NumberUtils.toInt(req.getParameter("privilege"));
		String content = req.getParameter("content");
		content = HttpUtils.tranlateSourceCode(content);
		String dateStr = req.getParameter("pubdate");
		Date date = MyUtils.parseDateCCT(dateStr, "yyy-MM-dd HH:mm");
        Post post = new Post(user, title, privilege, new Text(content), date, tags);
		
        PostService.getInstance().addPost(post);

        resp.sendRedirect("/blog/post");
	}



	/**
	 * 发布文章页面
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	private void newPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		if(!userService.isUserLoggedIn() || !userService.isUserAdmin()){
			return;
		}
		User user = userService.getCurrentUser();
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("userService", userService);
		root.put("user", user);
		root.put("config", ConfigureService.getInstance());
		root.put("spinpostlist", PostService.getInstance().getSpinPostList());
		root.put("focustab", "newpost");
		root.put("now", new Date());
		root.put("uri", req.getRequestURI());
		
		/* sidebar */
		WidgetService.getInstance().getSpecifiedWidget(root, "taglist", "recentpost");
		
		processTemplate(root, "newPost.html", resp);

	}
	
	/**
	 * 查看文章
	 * @param req
	 * @param resp
	 * @throws IOException 
	 */
	private void viewPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		long postid = NumberUtils.toLong(req.getParameter("postid"));
		if(postid == 0){
			error();
			return;
		}
		jalus.pojo.Post post = PostService.getInstance().getPostById(postid);
		if(!(userService.isUserLoggedIn() && userService.isUserAdmin())){
			MyUtils.processPost(post);
		}
		String errmsg = null;
		/* 评论验证码 */
		if(!userService.isUserLoggedIn()){
			String code = CaptchaUtils.random();
			HttpSession session = req.getSession();
			session.setAttribute("code", code);
			errmsg = (String) session.getAttribute("errmsg");
			session.removeAttribute("errmsg");
		}
		List<jalus.pojo.Comment> commentList = CommentService.getInstance().getCommentByPost(postid); 
		
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("errmsg", errmsg);
		root.put("post", post);
		root.put("commentList", commentList);
		root.put("user", user);
		/* 传递变量 */
		root.put("config", ConfigureService.getInstance());
		root.put("spinpostlist", PostService.getInstance().getSpinPostList());
		if(post.isSpined()){
			root.put("focustab", post.getTitle());
		}else{
			root.put("focustab", "article");
		}
		root.put("userService", userService);
		root.put("uri", req.getRequestURI());
		
		/* sidebar */
		WidgetService.getInstance().getSpecifiedWidget(root, "taglist", "recentpost", "recentcomment");
		
		processTemplate(root, "viewPost.html", resp);

	}
	/**
	 * 删除文章
	 * @param req
	 * @param resp
	 * @throws IOException 
	 */
	private void deletePost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		if(!userService.isUserLoggedIn() || !userService.isUserAdmin()){
			error();
			return;
		}
		
		long id = NumberUtils.toLong((req.getParameter("postid")));
		if(id == 0){
			error();
			return;
		}
		PostService postService = PostService.getInstance();
		postService.deletePostById(id);
		resp.sendRedirect("/blog/post");
		
	}
	
	/**
	 * 编辑文章页面
	 * @param req
	 * @param resp
	 * @throws IOException 
	 */
	private void editPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		if(!userService.isUserLoggedIn() || !userService.isUserAdmin()){
			return;
		}
		User user = userService.getCurrentUser();
		
		long postid = NumberUtils.toLong(req.getParameter("postid"));
		PostService postService = PostService.getInstance();
		jalus.pojo.Post post = postService.getPostById(postid);
		
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("userService", userService);
		root.put("user", user);
		root.put("post", post);
		root.put("config", ConfigureService.getInstance());
		root.put("spinpostlist", PostService.getInstance().getSpinPostList());
		root.put("focustab", "article");
		root.put("uri", req.getRequestURI());
		
		/* sidebar */
		WidgetService.getInstance().getAllWidget(root);
		
		processTemplate(root, "editPost.html", resp);
	}
	
	/**
	 * 文章列表
	 * @param req
	 * @param resp
	 * @throws IOException 
	 */
	private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		/*page*/
		//String offsetflag = req.getParameter("offsetflag");
		int pagenum = NumberUtils.toInt(req.getParameter("page"), 1);
		/*tag*/
		String tag = req.getParameter("tag");
		if(tag != null){
			tag = java.net.URLDecoder.decode(tag, "UTF-8");
		}
		/* 分页 */
		int totalPostNum = TagService.getInstance().getPostNum(tag);
		PostService postService = PostService.getInstance();
		int pagesize = ConfigureService.getInstance().getPostnumperpage();
		Pageindicator pageindicator = new Pageindicator(totalPostNum, pagenum, pagesize);
		List<jalus.pojo.Post> postList = postService.getPostList(tag, 
				pageindicator.getCurrentStartIndex(), pagesize);
		
		// 处理私有权限的文章
		if(!(userService.isUserLoggedIn() && userService.isUserAdmin())){
			MyUtils.processPostList(postList);
		}

		/* 传递变量 */
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("page", pageindicator);
		root.put("total", totalPostNum);
		root.put("postlist", postList);
		root.put("user", user);
		root.put("tag", tag);
		Map<String, String> parameterMap = new LinkedHashMap<String, String>();
		parameterMap.put("tag", tag);
		parameterMap.put("page", "");
		String baseUrl = HttpUtils.makeUrl("/blog/post", parameterMap);
		root.put("config", ConfigureService.getInstance());
		root.put("spinpostlist", PostService.getInstance().getSpinPostList());
		root.put("focustab", "article");
		root.put("userService", userService);
		root.put("uri", req.getRequestURI());
		root.put("page_base", baseUrl);
		
		/* sidebar */
		WidgetService.getInstance().getAllWidget(root);
		
		processTemplate(root, "postList.html", resp);
	}
	

	private void listArchive(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		/*page*/
		String archive = req.getParameter("archive");
		PostService postService = PostService.getInstance();
		List<jalus.pojo.Post> postList = postService.getPostListByMonth(archive);
		
		if(!(userService.isUserLoggedIn() && userService.isUserAdmin())){
			MyUtils.processPostList(postList);
		}

		/* 传递变量 */
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("postlist", postList);
		root.put("user", user);
		Map<String, String> parameterMap = new HashMap<String, String>();
		parameterMap.put("pagenum", "");
		String baseUrl = HttpUtils.makeUrl("/blog/post", parameterMap);
		root.put("config", ConfigureService.getInstance());
		root.put("spinpostlist", PostService.getInstance().getSpinPostList());
		root.put("focustab", "article");
		root.put("userService", userService);
		root.put("uri", req.getRequestURI());
		root.put("page_base", baseUrl);
		
		/* sidebar */
		WidgetService.getInstance().getAllWidget(root);
		
		processTemplate(root, "postList.html", resp);
	}
}
